#!/usr/bin/env python
# -*- coding:utf-8 -*-

from app import db
from utils.response_code import RET, error_map_EN

class AppointmentInfoService:
    
    @staticmethod
    def handle_appointment_status_change(record_id, new_status, appointment_controller, schedule_controller):
        """
        处理预约状态变更的业务逻辑
        :param record_id: 预约记录ID
        :param new_status: 新的预约状态
        :param appointment_controller: AppointmentInfoController 实例
        :param schedule_controller: ScheduleController 实例
        :return: dict
        """
        try:
            # 1. 获取当前预约记录
            appointment = appointment_controller.get(record_id=record_id)
            if appointment['code'] != "2000" or not appointment['data']:
                return {"code": "4001", "message": "预约记录不存在"}
            
            appointment_data = appointment['data'][0] if isinstance(appointment['data'], list) else appointment['data']
            
            # 2. 检查是否是从待确认(0)变更为已确认(1)
            if new_status != 1 or appointment_data['appointment_status'] != 0:
                # 如果不是从0改为1，走普通更新流程
                return appointment_controller.update_status(record_id=record_id, appointment_status=new_status)

            # 3. 获取该时间段的具体信息
            schedule = schedule_controller.get(time_id=appointment_data['time_id'])
            if schedule['code'] != "2000" or not schedule['data']:
                return {"code": "4002", "message": "时间段信息不存在"}

            schedule_data = schedule['data'][0] if isinstance(schedule['data'], list) else schedule['data']
            target_date = schedule_data['date']
            target_period = schedule_data['period']

            #相同时间段的其他咨询者被拒绝
            # 新增: 4. 查找该时间段的所有其他咨询者的预约
            other_appointments = appointment_controller.get(
                time_id=appointment_data['time_id']
            )

            # 新增: 5. 处理其他咨询者的预约
            if other_appointments['code'] == "2000" and other_appointments['data']:
                for other_app in other_appointments['data']:
                    # 跳过当前预约和已经是拒绝状态的预约
                    if (other_app['record_id'] != record_id and
                            other_app['client_id'] != appointment_data['client_id'] and
                            other_app['appointment_status'] not in [2, 6]):
                        # 将其他咨询者的预约状态更新为拒绝
                        appointment_controller.update_status(
                            record_id=other_app['record_id'],
                            appointment_status=2,
                            cancel_reason="该时间段已被其他咨询者预约"
                        )
            
            # 4. 查找该咨询者的所有预约记录
            client_appointments = appointment_controller.get(
                client_id=appointment_data['client_id']
            )
            
            if client_appointments['code'] == "2000" and client_appointments['data']:
                appointments_to_update = []
                
                # 5. 遍历所有预约记录
                for app in client_appointments['data']:
                    if app['record_id'] != record_id and app['appointment_status'] not in [2, 6]:
                        app_schedule = schedule_controller.get(time_id=app['time_id'])
                        if app_schedule['code'] == "2000" and app_schedule['data']:
                            app_schedule_data = app_schedule['data'][0] if isinstance(app_schedule['data'], list) else app_schedule['data']
                            
                            if (app_schedule_data['date'] == target_date and 
                                app_schedule_data['period'] == target_period):
                                appointments_to_update.append(app['record_id'])
            
            # 6. 批量更新状态
            for app_record_id in appointments_to_update:
                appointment_controller.update_status(
                    record_id=app_record_id,
                    appointment_status=6,
                    cancel_reason="与其他已确认预约时间冲突"
                )

            # 新增: 10. 更新时间段状态为已预约(1)
            schedule_update = schedule_controller.update(
                time_id=appointment_data['time_id'],
                status=1  # 1表示已预约
            )

            if schedule_update['code'] != "2000":
                # 如果更新失败，记录日志但不影响整体流程
                print(f"Warning: Failed to update schedule status: {schedule_update['message']}")

            # 7. 更新当前预约记录状态
            result = appointment_controller.update_status(
                record_id=record_id,
                appointment_status=new_status
            )
            
            return result

            
        except Exception as e:
            db.session.rollback()
            return {
                "code": "5000",
                "message": "服务器内部错误",
                "error": str(e)
            }
